<template>
  <div class="page">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button class="add-btn" type="primary" @click="openDialog('add',null)">新增</el-button>
            <span>共计{{ total }}条</span>
          </div>
          <div class="right">
            <el-form inline @submit.prevent>
              <el-form-item label="用户名">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入用户名"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="clientData"
        style="width: 100%"
        empty-text="暂无数据"
        :table-layout="tableLayout"
      >
        <el-table-column
          v-for="item in clientTableLabels"
          :key="item.id"
          :prop="item.prop"
          :label="item.label"
        ></el-table-column>
        <el-table-column>
          <template #default="data">
            <div class="icon-group">
              <el-tooltip effect="light" content="编辑" placement="top">
                <el-button icon="Edit" type="primary" @click="openDialog('edit', data.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="light" content="删除" placement="top">
                <el-button icon="Delete" @click="handleDelete(data.row.id)" type="danger"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:currentPage="current"
        v-model:page-size="pageSize"
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
  <el-dialog v-model="dialogVisible" :title="dialogFormTitle">
    <el-form :model="dialogForm" :rules="rules" ref="formRef">
      <el-form-item label="姓名" label-width="140px" prop="name">
        <el-input v-model="dialogForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="地址" label-width="140px" prop="address">
        <el-input v-model="dialogForm.address" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" label-width="140px" prop="gender">
        <el-select v-model="dialogForm.gender" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(dialogFormTitle === '新增' ? 'add' : 'edit')">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
defineOptions({
  name: "UserIndex"
});
import { ref, reactive, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import {
  getClientData,
  deleteClientData,
  addClientData,
  getClientById,
  editClientData
} from "@/api/client";
import { ElMessage, ElMessageBox } from "element-plus";
import { clientTableLabels, clientDataRules } from "@/miscellaneous";
const rules = reactive(clientDataRules);
const total = ref(0);
const tableLayout = ref("fixed");
const clientData = ref([]);
const current = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const dialogVisible = ref(false);
// 搜索相关
const searchKeyword = ref("");
const searchForm = reactive({
  keyword: ""
});
const dialogFormTitle = ref("");

const dialogForm = reactive({
  id: null,
  name: "",
  gender: "",
  address: ""
});
const formRef = ref(null);
const loadData = async () => {
  loading.value = true;
  try {
    const res = await getClientData({
      keyword: searchKeyword.value,
      page: current.value,
      pageSize: pageSize.value
    });
    clientData.value = res.data.rows;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    ElMessage.error(error.message);
    loading.value = false;
  }
};
const handleCurrentChange = value => {
  current.value = value;
  loadData();
};

// 搜索处理函数
const handleSearch = () => {
  searchKeyword.value = searchForm.keyword.trim();
  current.value = 1; // 搜索时重置到第一页
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = "";
  searchKeyword.value = "";
  current.value = 1;
  loadData();
};

// 删除处理函数
const handleDelete = async id => {
  try {
    await ElMessageBox.confirm("确定要删除这条客户数据吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 调用删除API
    await deleteClientData(id);

    // 智能分页处理 - 当删除当前页最后一条数据时，自动跳转到上一页
    if (current.value > 1 && clientData.value.length === 1) {
      current.value--;
    }

    ElMessage.success("删除成功!");

    // 重新加载数据，更新列表
    await loadData();
  } catch (error) {
    // 错误处理，区分用户取消和API调用失败
    if (error === "cancel") {
      // 用户点击取消，不做任何操作
      console.log("用户取消了删除操作");
    } else {
      // API调用失败
      console.error("删除失败:", error);
      ElMessage.error(error.message || "删除失败，请重试");
    }
  }
};
// 打开对话框
const openDialog = async (type, id) => {
  dialogVisible.value = true;

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 重置表单
  Object.assign(dialogForm, {
    id: null,
    name: "",
    gender: "",
    address: ""
  });
  // 无id 新增
  if (!id) {
    dialogFormTitle.value = "新增";
    // 重置表单
  } else {
    dialogFormTitle.value = "编辑";
    // 数据回显
    try {
      const res = await getClientById(id);
      if (res.code === 200) {
        Object.assign(dialogForm, res.data);
      }
    } catch (error) {
      ElMessage.error(error.message || "获取客户数据失败");
    }
  }
};

// 统一的提交方法，根据类型处理新增或编辑
const submitForm = async type => {
  // 表单验证
  if (!formRef.value) {
    ElMessage.error("表单未初始化");
    return;
  }

  try {
    await formRef.value.validate();

    let res;
    if (type === "add") {
      // 新增操作
      res = await addClientData(dialogForm);
      if (res.code === 200) {
        ElMessage.success("新增成功");
      }
    } else if (type === "edit") {
      // 编辑操作
      res = await editClientData(dialogForm);
      if (res.code === 200) {
        ElMessage.success("编辑成功");
      }
    }

    if (res.code === 200) {
      dialogVisible.value = false;
      // 重新加载数据
      await loadData();
    }
  } catch (error) {
    // 表单验证失败或API调用失败
    if (error === false) {
      ElMessage.error("请填写完整信息！");
    } else {
      ElMessage.error(error.message || "操作失败，请重试");
    }
  }
};
onMounted(() => {
  loadData();
});
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .right {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.icon-group {
  display: flex;
  gap: 8px;

  .el-button {
    padding: 4px 8px;
  }
}
</style>
